package com.example.su_shi_tan_mine.child

import android.content.Context
import android.util.Log
import android.view.View
import android.widget.ProgressBar
import android.widget.TextView
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemClickListener
import com.example.su_shi_tan_bas_lib.adapter.JssBaseQuickAdapter
import com.example.su_shi_tan_bas_lib.adapter.JssBaseViewHolder
import com.example.su_shi_tan_bas_lib.networking.RestClient
import com.example.su_shi_tan_bas_lib.utils.PixUtils
import com.example.su_shi_tan_mine.R
import com.example.su_shi_tan_mine.child.bean.AreaItemBean
import com.example.su_shi_tan_mine.config.CITY
import com.example.su_shi_tan_mine.config.COMMUNITY
import com.example.su_shi_tan_mine.config.DISTRICT
import com.example.su_shi_tan_mine.config.PROVINCE
import com.google.android.material.tabs.TabLayout
import com.lxj.xpopup.core.BottomPopupView
import com.lxj.xpopup.interfaces.OnSelectListener

class SelectLocationPop(context: Context) : BottomPopupView(context), OnItemClickListener,
    TabLayout.OnTabSelectedListener {

    override fun getPopupHeight(): Int {
        return PixUtils.dp2px(380)
    }


    private var isAfterDistrict = false

    fun setIsAfterDistrict(isAfterDistrict: Boolean): SelectLocationPop {
        this.isAfterDistrict = isAfterDistrict

        return this
    }

    private val mTabLayout by lazy {
        findViewById<TabLayout>(R.id.mTabLayout)
    }

    private val mRecyclerView by lazy {
        findViewById<RecyclerView>(R.id.mRecyclerView)
    }

    private lateinit var mAdapter: JssBaseQuickAdapter<AreaItemBean>

    private val mProgressBar by lazy {
        findViewById<ProgressBar>(R.id.mProgressBar)
    }

    private val sureTv by lazy {
        findViewById<TextView>(R.id.sureTv)
    }

    private val mData = mutableListOf<AreaItemBean>()

    private val mAreaTypeTransfer = mutableMapOf(
        "$PROVINCE" to "$CITY",
        "$CITY" to "$DISTRICT",
        "$DISTRICT" to ""
    )

    private var selectedItem: AreaItemBean? = null

    private val resTv by lazy {
        findViewById<TextView>(R.id.resTv)
    }


    private var onSelectListener: OnSelectListener? = null

    fun setOnSelectListener(onSelectListener: OnSelectListener): SelectLocationPop {
        this.onSelectListener = onSelectListener
        return this
    }


    override fun getImplLayoutId() = R.layout.select_location_pop

    override fun onCreate() {
        super.onCreate()
        if (isAfterDistrict) {
            mAreaTypeTransfer["$DISTRICT"] = "$COMMUNITY"
        }


        sureTv.setOnClickListener {
            val addresses = addresses()
            if (addresses.isEmpty()) {
                Toast.makeText(context, "请选择具体地址", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            onSelectListener?.onSelected(addresses)

            dismiss()

        }


        mRecyclerView.setHasFixedSize(true)
        mRecyclerView.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        mAdapter =
            object : JssBaseQuickAdapter<AreaItemBean>(R.layout.select_location_item_pop, mData) {

                override fun convert(holder: JssBaseViewHolder?, item: AreaItemBean?) {
                    super.convert(holder, item)
                    val textColor = if (selectedItem?.name == (item?.name
                            ?: "textColor")
                    ) R.color.PrimaryColor else R.color.blackAlpha55

                    holder?.setText(R.id.textTv, item?.name)
                        ?.setTextColorRes(R.id.textTv, textColor)
                }

            }
        mRecyclerView.adapter = mAdapter

        mProgressBar.visibility = VISIBLE

        mAdapter.setOnItemClickListener(this)

        mTabLayout.addOnTabSelectedListener(this)


        getLocation()
    }

    private fun addresses(): List<AreaItemBean?> {
        val ls= mutableListOf<AreaItemBean?>()
        val tabCount=mTabLayout?.tabCount?:0
        for (e in 0 until  tabCount){
            val tag = mTabLayout?.getTabAt(e)?.tag
            if (tag is AreaItemBean){
                ls.add(tag)
            }
        }
        return ls
    }


    private fun getLocation() {
        resTv?.visibility = GONE

        mProgressBar.visibility = VISIBLE

        sureTv.visibility = GONE


        RestClient.builder()
            .url(R.string.get_area_list)
            .success {
                Log.d("getLocation", "getLocation: $it")
                parseArea(it)
            }.error { _, msg ->
                onFailed(msg)
            }
            .failure {
                onFailed("网络异常")
            }
            .build()
            .get()


    }

    private fun parseArea(data: String?) {
        mProgressBar.visibility = GONE
        sureTv.visibility = VISIBLE
        var mArray = JSON.parseArray(data, AreaItemBean::class.java)
        mArray = reSettingArray(mArray, null)
        loadListDate(mArray)


    }

    private fun reSettingArray(
        mArray: List<AreaItemBean>?,
        parent: AreaItemBean?
    ): MutableList<AreaItemBean> {
        val ls = mutableListOf<AreaItemBean>()
        if (mArray != null) {
            for (e in mArray) {
                e.parent = parent
                e.level = (e.parent?.level ?: 0) + 1
                e.child = reSettingArray(e.child, e)
            }
            ls.addAll(mArray)
        }

        return ls
    }


    private fun onFailed(msg: String?) {
//        if (selectedItem?.areaType != DISTRICT) {
        resTv?.text = msg
        resTv?.visibility = VISIBLE
//        }

    }


    private fun loadListDate(array: List<AreaItemBean>) {
        resTv?.visibility = GONE
        mAdapter.clears()
        mAdapter.addData(array)
        if (mAdapter.data.size <= 0) {
            onFailed("暂无数据")
        }
    }


    override fun onItemClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {

        val item = mAdapter.getItem(position)

        item?.brother?.clear()
        item?.brother?.addAll(mAdapter.data)

        selectedItem = item


        var tabIndex = -100

        for (index in 0 until mTabLayout.tabCount) {
            val tab = mTabLayout.getTabAt(index)
            val currentTabTag = tab?.tag as AreaItemBean
            if (currentTabTag.level == item.level) {
                tabIndex = index
                break
            }
        }

        if (tabIndex >= 0) {

            val tabAt = mTabLayout.getTabAt(tabIndex)

            mTabLayout.selectTab(tabAt, true)

            tabAt?.text = item.name
            tabAt?.tag = item

        } else {
            mTabLayout.addTab(
                mTabLayout.newTab()
                    .setText(item.name)
                    .setTag(item),
                true
            )
        }

    }

    override fun onTabSelected(tab: TabLayout.Tab?) {
//        Log.d("onTab", "onTabSelected: ")
        val lastTabIndex = mTabLayout.tabCount - 1
//
        val remove = mTabLayout.tabCount - 1 - (tab?.position ?: lastTabIndex)
//
        for (index in 0 until remove) {
            mTabLayout.removeTabAt(mTabLayout.tabCount - 1)
        }
//
        val text = tab?.text ?: ""

        if (text.isEmpty()) {
            return
        }
        val currentTabTag = tab?.tag as AreaItemBean

        val item = if (currentTabTag.level == selectedItem?.level)
            currentTabTag.child
        else
            currentTabTag.brother

        loadListDate(item ?: emptyList())

    }

    override fun onTabUnselected(tab: TabLayout.Tab?) {

    }

    override fun onTabReselected(tab: TabLayout.Tab?) {
//        Log.d("onTab", "onTabReselected: ")
        val currentTabTag = tab?.tag as AreaItemBean
        val item = if (currentTabTag.level == selectedItem?.level)
            currentTabTag.child
        else
            currentTabTag.brother
        loadListDate(item ?: emptyList())

    }

    override fun dismiss() {
        super.dismiss()
        onSelectListener = null
    }

    override fun onDismiss() {
        super.onDismiss()
        mTabLayout.removeOnTabSelectedListener(this)
    }

    interface OnSelectListener {
        fun onSelected(ls: List<AreaItemBean?>)
    }
}